package hu.debrecen.adastra.card.config;

import javax.inject.Inject;
import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.AdviceMode;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.jpa.AbstractEntityManagerFactoryBean;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@ComponentScan(basePackages = { "hu.debrecen.adastra.card" }, excludeFilters = { @Filter(Configuration.class), @Filter(Controller.class) })
@ImportResource(value = { "classpath:/META-INF/spring/application-context.xml", "classpath:/META-INF/spring/app-database-context.xml" })
@PropertySource(value = { "classpath:/META-INF/application.properties" })
@EnableTransactionManagement(mode = AdviceMode.ASPECTJ)
@EnableCaching(mode = AdviceMode.ASPECTJ)
public class MainConfig {

	private static final Logger LOGGER = LoggerFactory.getLogger(MainConfig.class);

	@Inject
	private Environment environment;

	@Inject
	private DataSource dataSource;

	@Bean
	public PlatformTransactionManager transactionManager() {
		MainConfig.LOGGER.debug("Create JpaTransactionManager.");
		return new JpaTransactionManager(this.entityManagerFactory().getObject());
	}

	@Bean
	public AbstractEntityManagerFactoryBean entityManagerFactory() {

		MainConfig.LOGGER.debug("Create EntityManagerFactory.");

		HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
		hibernateJpaVendorAdapter.setShowSql(false);
		hibernateJpaVendorAdapter.setGenerateDdl(true);

		LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
		emf.setDataSource(this.dataSource);
		emf.setJpaVendorAdapter(hibernateJpaVendorAdapter);
		emf.setPersistenceUnitName("adAstra-PersistenceUnit");
		emf.getJpaPropertyMap().put("hibernate.hbm2ddl.auto", this.environment.getProperty("hibernate.hbm2ddl.auto"));

		return emf;
	}

}
